import { constantRoutes } from '@/router'
import { getCurrentUserMenuTree } from '@/api/common/currentLoginUser'
import Layout from '@/layout/index'
import iFrame from '@/components/iFrame';
import ParentView from '@/components/ParentView';
import InnerLink from '@/layout/components/InnerLink'
import { queryCurrentLoginUserInfoRes } from "@/api/common/currentLoginUser"

const permission = {
  state: {
    getRouteFlag: false,
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    permissions: [],
    userId:'0',
    // 用户昵称
    realName: '',
    // 个性签名
    motto: '',
    // 名片背景
    visitCardBag: require('@/assets/images/chat/default-user-banner.png'),
    // 个性头像
    headPortrait: ''
  },
  mutations: {
    GET_ROUTE_FLAG: (state, flag) => {
      state.getRouteFlag = flag
    },
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      // 顶部导航菜单默认添加统计报表栏指向首页
    /*  const index = [{
        path: 'index',
        meta: { title: '统计报表', icon: 'dashboard'}
      }]
      state.topbarRouters = routes.concat(index);*/
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_NAME: (state, realName) => {
      state.realName = realName
    },
    SET_AVATAR: (state, headPortrait) => {
      state.headPortrait = headPortrait
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_MOTTO: (state, motto) => {
      state.motto = motto
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getCurrentUserMenuTree().then(res => {
          if (res&&res.errorCode === 0) {
            //重新获取用户信息
            queryCurrentLoginUserInfoRes().then(userInfoRes => {
              const defaultAvatar = require('@/assets/images/chat/detault-avatar.jpg')
              const userInfo = userInfoRes.data;
              commit('SET_AVATAR', userInfo.headPortrait? userInfo.headPortrait : defaultAvatar)
              commit('SET_NAME', userInfo.realName)
              commit('SET_USER_ID', userInfo.userId)
              commit('SET_MOTTO', userInfo.motto)
            });
            //获取权限编码BEG
            const resultArr = []
            const permsData = buildPerms(resultArr,res.data)
            //获取权限编码end
            const rdata = buildMenus(res.data)
            const sdata = buildMenus(res.data);
            const sidebarRoutes = filterAsyncRouterNew(sdata)
            const rewriteRoutes = filterAsyncRouterNew(rdata, false, true)
            rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
            commit('SET_ROUTES', rewriteRoutes)
            commit('GET_ROUTE_FLAG', true)
            commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            commit('SET_PERMISSIONS', permsData)
            resolve(rewriteRoutes)
          }else {
            //resolve(res)
          }
        })
      })
    }
  }
}


/**
 * 处理用户权限
 * @param resultArr
 * @param asyncMenus
 */
function buildPerms(resultArr,asyncMenus){
  asyncMenus.forEach((menu, index) => {
    resultArr.push(menu.menuCode)
    if (menu.children){
      buildPerms(resultArr,menu.children);
    }
  })
  return resultArr
}


/**
 * 处理菜单变成路由模式
 * @param asyncMenus
 */
function buildMenus(asyncMenus){
  const result = []
  asyncMenus.forEach((menu, index) => {
    let router = {}
    let component = getComponent(menu);
    router.hidden=menu.menuCacheCode==='YES'
    router.name=getRouteName(menu);
    router.path=getRouterPath(menu);
    router.component= component;
    //设置默认图标
    let icon = ''
    if (menu.menuIcon) {
      icon = menu.menuIcon
    }
    //外链
    let link= null;
    if (isMenuFrameCode(menu)){
      link = menu.component
    }
    router.meta = {
      'title': menu.menuName,
      'icon': icon,
      'noCache':false,
      'noRequireLogin':false,
      'link':link
    }
    if (checkChildrenDir(menu)&&menu.children){
      router.alwaysShow = true;
      router.redirect = "noRedirect";
      router.children=buildMenus(menu.children);
    }else if ((isParentMenu(menu)&&!checkChildrenDir(menu))){
      router.children=[
        {
          path: ''+menu.menuCode,
          component: menu.component,
          name: menu.menuName,
          meta: { title: menu.menuName, icon: icon, noCache: false,'noRequireLogin':false}
        },
      ]
    }
    result.push(router)
  })
  return result
}


/**
 * 判断是否有下级并且有导航类型
 * @param menu
 */
function checkChildrenDir(menu) {
  return menu.children && menu.children.length > 0 && (menu.children.filter(o => o.menuTypeCode === 'NAVIGATION').length >= 1)
}

/**
 * 获取路由名称
 * @param menu
 */
function getRouteName(menu) {
  return menu.menuCode;
}

/**
 * 判断是不是一级菜单
 * @param menu
 */
function isParentMenu(menu) {
  return menu.parentId === '-1';
}

/**
 * 判断是不是外链
 * @param menu
 */
function isMenuFrameCode(menu) {
  return menu.menuFrameCode === 'YES';
}

/**
 * 获取路由组件
 * @param menu
 */
function getComponent(menu) {
 //如果是外链
  if ((isParentMenu(menu)&&checkChildrenDir(menu))){
    return "Layout";
  }else if ((isParentMenu(menu)&&!checkChildrenDir(menu))){
    return "Layout";
  }else if(!isParentMenu(menu)&&isMenuFrameCode(menu)){
    return "InnerLink";
  }else if(checkChildrenDir(menu)){
    return "ParentView"
  }else {
    if (menu.component != null && menu.component !== '' && menu.component !== undefined) {
      return menu.component
    } else {
      return "ParentView"
    }
  }
}
/**
 * 获取路由路径
 * @param menu
 */
function getRouterPath(menu) {
  if (isParentMenu(menu)){
    if (isMenuFrameCode(menu)){
      return menu.component
    }else{
      return "/"+menu.menuCode
    }
  }else {
    return ""+menu.menuCode
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouterNew(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      }else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
       route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouterNew(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}


export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default permission
